﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF_PathSearchUtil.data_access;
using WPF_PathSearchUtil.entity;
using WPF_PathSearchUtil.service;
using WPF_PathSearchUtil.utils;
using WPF_PathSearchUtil.views;

namespace WPF_PathSearchUtil
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public delegate void FindFormConfirmEventHandler(string findWord);
        private ObservableCollection<PathInfo> fileList;
        private ObservableCollection<ObservableCollection<String>> fileListStr;
        private ObservableCollection<int> findResult;   
        private String filePath;
        private String findWord;
        private int indexNow;  
        private int[] IsDESC = { 0, 0, 0, 0, 0 };
        private CSVReadOrWrite access;

        public MainWindow()
        {
            InitializeComponent();
            fileList = new ObservableCollection<PathInfo>();
            fileListStr = new ObservableCollection<ObservableCollection<String>>
            {
                new ObservableCollection<String>()
            };
            findResult = new ObservableCollection<int>();
            FileDataGrid.ItemsSource = fileListStr;
            //access = new BackendClient();
            access = new LocalClient();
        }

        private void Window_KeyDown(object sender, Object e)
        {
            MessageBox.Show(e.GetType().ToString());
            //if (e.Key == Key.Escape)    Close();
            //if (e.Key == Key.F1) ImCSV.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            //if (e.Key == Key.F3) Next.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            //if (e.Key == Key.F7) Find.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            //if (e.Key == Key.F8) Withdraw.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            //if (e.SystemKey == Key.F10) ExCSV.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
        }

        private void Withdraw_Click(object sender, RoutedEventArgs e)
        {
            filePath = FindPath.Text;
            if (filePath == null || filePath.Length <= 0) 
            {
                MessageBox.Show("请输入要检索的路径。","提示");
                return;
            }
            fileList.Clear();
            bool isChecked = IsChecked.IsChecked ?? false;
            Resp resp = LoadFileList.WithdrawPath(ref fileList, filePath, isChecked);
            if (resp.Code == 0)
            {
                ListConvert.ListToStr(ref fileListStr, fileList);
                
            }
            else
            {
                MessageBox.Show(resp.Message,"提示");
            }
        }

        private void Find_Click(object sender, RoutedEventArgs e)
        {
            if (fileList.Count <= 0)
            {
                MessageBox.Show("没有可搜索的列表。", "提示");
                return;
            }
            FindForm findForm = new FindForm();
            findForm.FindFormConfirm += FindPathWord;
            findForm.ShowDialog();
        }

        private void Next_Click(object sender, RoutedEventArgs e)
        {
            if (findResult.Count <= 0)
            {
                MessageBox.Show("当前没有要进行检索的关键字。", "提示");
                return;
            }
            if (findResult.Count == 1)
            {
                FindPathWords.FindResult(ref findResult, fileList, findWord, 1);
                if (findResult.Count == 1)
                {
                    MessageBox.Show("这已经是最后一条。", "提示");
                    return;
                }
            }
            if (findResult.Count > 1)
            {
                FileDataGrid.UnselectAll();
                int index = findResult.IndexOf(indexNow);
                if (index == findResult.Count - 1)
                {
                    FileDataGrid.SelectedIndex = findResult[0];
                    indexNow = findResult[0];
                }
                else
                {
                    FileDataGrid.SelectedIndex = findResult[index + 1];
                    indexNow = findResult[index + 1];
                }
            }
        }

        /// <summary>
        /// CSV 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExCSV_Click(object sender, RoutedEventArgs e)
        {
            if (fileList.Count <= 0)
            {
                MessageBox.Show("没有可导出的列表。", "提示");
                return;
            }
            var fileData = new
            {
                fileList = fileListStr
            };
            if (access is BackendClient)
            {
                
                Resp resp = access.Write("fileInfos/save", HttpMethod.Post, fileData);
                if (resp.Code != 0)
                {
                    MessageBox.Show(resp.Message, "提示");
                    return;
                }
                if (resp.Code == 0)
                {
                    Dictionary<String, Object> response = (Dictionary<string, object>)resp.Date;
                    if (Convert.ToInt64(response["code"]) == 0)
                    {
                        MessageBox.Show("导出成功。", "提示");
                    }
                    else
                    {
                        MessageBox.Show("导出失败，" + response["message"].ToString(), "提示");
                    }
                }
            }
            if (access is LocalClient)
            {
                System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
                if (folderDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    String exPath = folderDlg.SelectedPath;
                    Resp resp = access.Write(exPath,fileListStr);
                    if (resp.Code != 0)
                    {
                        MessageBox.Show(resp.Message, "提示");
                    }
                    else
                    {
                        MessageBox.Show("成功，导出路径为：" + resp.Date, "提示");
                    }
                }
            }
        }

        private void ImCSV_Click(object sender, RoutedEventArgs e)
        {
            if (access is BackendClient)
            {
                Resp resp = access.Read("fileInfos/get", HttpMethod.Get, null);
                if(resp.Code != 0)
                {
                    MessageBox.Show(resp.Message, "提示");
                    return;
                }
                else
                {
                    Dictionary<String, Object> response = (Dictionary<string, object>)resp.Date;
                    if (Convert.ToInt64(response["code"]) == 0)
                    {
                        fileList.Clear();
                        fileListStr.Clear();
                        JArray list = (JArray)response["data"];
                        ListConvert.JArrayToList(ref fileListStr, list);
                        ListConvert.StrToList(fileListStr, ref fileList);
                        MessageBox.Show("读取成功。", "提示");
                    }
                    else
                    {
                        MessageBox.Show("读取失败，" + response["message"].ToString(), "提示");
                    }    
                }
            }
            if (access is LocalClient)
            {
                System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    String imPath = openFileDialog.FileName;
                    Resp resp = access.Read(imPath);
                    if (resp.Code != 0)
                    {
                        MessageBox.Show(resp.Message, "提示");
                        return;
                    }
                    else
                    {
                        fileList.Clear();
                        fileListStr.Clear();
                        ObservableCollection<ObservableCollection<String>> list = (ObservableCollection<ObservableCollection<string>>)resp.Date;
                        foreach (ObservableCollection<String> value in list)
                        {
                            fileListStr.Add(value);
                        }
                        ListConvert.StrToList(fileListStr,ref fileList);
                        MessageBox.Show("读取成功。", "提示");
                    }
                }
            }
        }

        private void FileDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
        {
            string column = e.Column.SortMemberPath;
            int columnIndex = int.Parse(column.Substring(1,1));
            e.Handled = true;
            for (int i = 0; i < IsDESC.Length; i++)
            {
                //当前点击列已排序，则反转list
                if (IsDESC[columnIndex] == 1)
                {
                    IsDESC[columnIndex] = 0;
                    fileList = new ObservableCollection<PathInfo>(fileList.Reverse());
                    ListConvert.ListToStr(ref fileListStr, fileList);
                    return;
                }
            }
            List<PathInfo> fileInfos = new List<PathInfo>(fileList);
            if (columnIndex == 0)
            {
                fileInfos = fileInfos.OrderBy(x => x.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (columnIndex == 1)
            {
                fileInfos = fileInfos.OrderBy(x => x.FilePath).ThenBy(y => y.FileName).ToList();
            }
            if (columnIndex == 2)
            {
                fileInfos = fileInfos.OrderBy(x => x.FileType).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (columnIndex == 3)
            {
                fileInfos = fileInfos.OrderBy(x => x.FileSize).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (columnIndex == 4)
            {
                fileInfos = fileInfos.OrderBy(x => x.FileDate).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            //每次只能有一个列在排序
            for (int i = 0; i < IsDESC.Length; i++)
            {
                IsDESC[i] = 0;
            }
            IsDESC[columnIndex] = 1;
            fileList.Clear();
            foreach (var file in fileInfos)
            {
                fileList.Add(file);
            }
            ListConvert.ListToStr(ref fileListStr, fileList);

        }

        private void Done_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void FindPathWord(string findWord)
        {
            this.findWord = findWord;
            FindPathWords.FindResult(ref findResult, fileList, findWord, 0);
            if (findResult.Count <= 0)
            {
                FindPathWords.FindResult(ref findResult, fileList, findWord, 1);
            }
            if (findResult.Count <= 0)
            {
                MessageBox.Show("検索条件に一致するデータは見つかりません。", "提示");
                return;
            }
            FileDataGrid.UnselectAll();
            FileDataGrid.SelectedIndex = findResult[0];
            indexNow = findResult[0];
        }


        //todo selectionchanged
        private void FileDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (FileDataGrid.SelectedItem != null)
            {
                FileDataGrid.ScrollIntoView(FileDataGrid.SelectedItem);
            }
        }

        private void SelectPath_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
            if (folderDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FindPath.Text = folderDlg.SelectedPath;
            }
        }
    }
}
